import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../views/Layout.vue'
import Dashboard from '../views/Dashboard.vue'
import UserManagement from '../views/UserManagement.vue'
import PermissionManagement from '../views/PermissionManagement.vue'
import Settings from '../views/Settings.vue'
import Login from '../views/Login.vue'

const routes = [
  {
    path: '/login',
    component: Login,
    meta: { title: '登录' }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      { path: 'dashboard', component: Dashboard, meta: { title: '首页' } },
      { path: 'user', component: UserManagement, meta: { title: '用户管理' } },
      { path: 'permission', component: PermissionManagement, meta: { title: '权限管理' } },
      { path: 'settings', component: Settings, meta: { title: '系统设置' } },
      // 多级菜单演示
      {
        path: 'nested',
        meta: { title: '路由嵌套' },
        children: [
          {
            path: 'menu1',
            meta: { title: '菜单1' },
            children: [
              { path: 'menu1-1', component: Dashboard, meta: { title: '菜单1-1' } },
              { path: 'menu1-2', component: Dashboard, meta: { title: '菜单1-2' } }
            ]
          },
          { path: 'menu2', component: Dashboard, meta: { title: '菜单2' } }
        ]
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 登录守卫
router.beforeEach((to, from, next) => {
  const isLogin = localStorage.getItem('isLogin')
  if (to.path !== '/login' && !isLogin) {
    next('/login')
  } else if (to.path === '/login' && isLogin) {
    next('/dashboard')
  } else {
    next()
  }
})

export default router
